package com.cqyc.network.http

import com.cqyc.network.Response
import com.cqyc.network.getid.GetMyInformationBox
import com.cqyc.network.utils.ToastUtils
import retrofit2.Call

open class DataCallBack<T>(
    val onResponse: (T) -> Unit,
    private val onFailure: ((Throwable) -> Unit)? = null
) : retrofit2.Callback<Response<T>> {
    override fun onResponse(call: Call<Response<T>>, response: retrofit2.Response<Response<T>>) {
        if (!response.isSuccessful) {
            onFailure(call, Exception(response.message()))
            return
        }
        val result = response.body()
        if (result?.code == 7000) {
            onFailure(call, Exception(result?.msg))
            GetMyInformationBox.postDisconnection()
            return
        }
        if (result?.code != 2000) {
            onFailure(call, Exception(result?.msg))
            return
        }
        if (result.data == null) {
            onFailure(call, Exception("数据为空"))
            return
        }
        onResponse(result.data)
    }

    override fun onFailure(call: Call<Response<T>>, t: Throwable) {
        if (onFailure != null) {
            onFailure.invoke(t)
        } else {
            ToastUtils.showLong(t.message)
        }
    }
}